﻿/*===================================================
* CLR版本  : 4.0.30319.42000 
* 类名称   : ObjectPool
* 文 件 名 : ObjectPool 
* 类描述   :
* 创建人   : oream
* 创建时间 : 2018/3/4 0:51:48
* 修改人   : 
* 修改时间 :
* 版本： @version 1.0
=====================================================*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
  public class ObjectPool
  {

    private Dictionary<Type, Queue<Disposer>> dicObjectPool = new Dictionary<Type, Queue<Disposer>>();

    /// <summary>
    /// 获取对象池中对对象(如果没有就生成)
    /// </summary>
    /// <param name="type"></param>
    public Disposer FetchObject(Type type)
    {
      Queue<Disposer> tmpDisposers;
      if (!this.dicObjectPool.TryGetValue(type, out tmpDisposers))
      {
        tmpDisposers = new Queue<Disposer>();
        this.dicObjectPool.Add(type, tmpDisposers);
      }
      Disposer tmpObj;
      if (tmpDisposers.Count > 0)
      {
        tmpObj = tmpDisposers.Dequeue();
        tmpObj.Id = IDGenerater.GenerateId();
        tmpObj.IsFromPool = true;
        return tmpObj;
      }
      tmpObj = Activator.CreateInstance(type) as Disposer;
      tmpObj.IsFromPool = true;
      return tmpObj;
    }
    /// <summary>
    /// 获取对象池中对对象(如果没有就生成)
    /// </summary>
    /// <param name="type"></param>
    public T FetchObject<T>() where T : Disposer
    {
      T tmp = (T)this.FetchObject(typeof(T));
      return tmp;
    }

    /// <summary>
    /// 从新生成
    /// </summary>
    public void Recycle(Disposer disposer)
    {
      Type tmpType = disposer.GetType();
      Queue<Disposer> tmp;
      if (!dicObjectPool.TryGetValue(tmpType, out tmp))
      {
        tmp = new Queue<Disposer>();
        dicObjectPool.Add(tmpType, tmp);
      }
      tmp.Enqueue(disposer);
    }

  }
}
